<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="20">

            <a-col :md="4" :sm="24">
              <a-form-item label="名称">
                <a-input v-model="queryParam.name" placeholder="请输入商户名称"/>
              </a-form-item>
            </a-col>

            <!-- <a-col :md="4" :sm="24">
             <a-form-item label="标识">
               <a-select v-model="queryParam.type" placeholder="请选择">
                 <a-select-option value="1">分销商</a-select-option>
                 <a-select-option value="2">渠道商</a-select-option>
                 <a-select-option value="3">批发商</a-select-option>
               </a-select>
             </a-form-item>
           </a-col> -->
           
           <!-- <a-col :md="4" :sm="24">
             <a-form-item label="业务员" placeholder="请选择">
              <a-input v-model="queryParam.username" placeholder="请输入业务员用户名"/>
             </a-form-item>
           </a-col> -->

            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd" v-action:addmerchantbtn2>新建</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        :rowKey="(record,index)=>{return index}"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        
        <span slot="baseInfo" slot-scope="text, record">
          <div style="display: flex;">
            <div>
              <div>{{record.name}}</div>
              <div>
                标识：
                <a-tag :color="record.type == 1?'pink':record.type == 2?'green':'cyan'">
                  {{record.typename}}
                </a-tag>
              </div>
              <div>AK：{{record.ak || '待生成'}}</div>
              <div>SK：{{record.sk || '待生成'}}</div>
            </div>
            <!-- <div class="margL10">
              <div>
                账号：{{record.username}}
              </div>
              <div>
                创建时间：<br>
                {{record.createtime||'--'}}
              </div>
              <div>
                有效时间：<br>
                {{record.validtime||'--'}}
              </div>
            </div> -->
          </div>
        </span>
        
        <span slot="account" slot-scope="text, record">
          <div>
            账号：{{record.username}}
          </div>
          <div>
            创建时间：<br>
            {{record.createtime||'--'}}
          </div>
          <div>
            有效时间：<br>
            {{record.endtime}}
          </div>
        </span>
        <span slot="username" slot-scope="text, record">
          <!-- <a-avatar :src="record.avatar" :size="54" style="margin-bottom:5px"/> -->
          <div>{{record.username}}</div>
          <!-- <div>{{record.stu_id}}</div> -->
        </span>
        <span slot="salesman" slot-scope="text, record">
          <span>{{record.user_name}}</span>
        </span>
        <span slot="info" slot-scope="text, record">
          <div>授信额度:{{record.credit_line}}</div>
          <div>可用授信额度:{{record.acredit_line}}</div>
          <div>可用余额:{{record.available_balance}}</div>
          <div>充值金额:{{record.recharge}}</div>
          <div>扣除金额:{{record.deduction}}</div>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <!-- <a @click="open(record)" v-action:release_open2>详情</a> -->
            <!-- <a-divider type="vertical"/> -->
            <a @click="handleEdit(record)" v-action:editmerchantbtn2>修改</a>
            <a-divider type="vertical"/>
            <a-popconfirm
              v-action:deletemerchantbtn2
              title="确定删除此项吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirm(record)"
              @cancel="cancel(record)"
            >
              <a>删除</a>
            </a-popconfirm>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        :userList="userList"
        @cancel="handleCancel"
        @ok="handleOk"
      />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'
// import { getMember, addMember, delMember } from '@/api/system'

// import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './modules/CreateForm'
// import UpdataForm from './modules/UpdataForm'

import merchantApi from '@/api/merchant.js'

import {
  getUserList,
  getRoLeList 
} from '@/api/system'

const columns = [
  {
    title: '编号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '基础信息',
    scopedSlots: { customRender: 'baseInfo' }
  },
  {
    title: '账号',
    scopedSlots: { customRender: 'account' }
  },
  {
    title: '额度信息',
    dataIndex: 'info',
    scopedSlots: { customRender: 'info' }
  },
  {
    title: '绑定业务员',
    scopedSlots: {customRender: 'salesman'}
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '130px',
    scopedSlots: { customRender: 'action' }
  }
]
const merchant = {
  'data': [
    {
      id:1,
      name: '王五',
      isFlag: '分销商',
      AK: 'AK1006',
      SK: 'Sk1008',
      endTime: '2016-5-20',
      rmb: 50,
      username: 'admin',
      password: 123456,
      quota: 100,
      czye: 10000,
      ccye: 5000,
      user_id:3,
      salesman: '张三'
    },
  ],
  'pageSize': 10,
  'pageNo': 1,
  'totalPage': 6,
  'totalCount': 2
}

export default {
  components: {
    STable,
    CreateForm
  },
  data () {

    this.columns = columns
    return {
      userList:[],
      visibles: false,
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        // console.log('loadData request parameters:', requestParameters)
        // return new Promise((res, rej) => {
        //   res()
        // }).then(res => {
        //   return merchant
        // })import supplierApi from '@/api/supplier.js'
        return merchantApi.MerchantPage(requestParameters).then(res => {
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  created() {
    this.getRoleList()
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  mounted() {
    console.log("this.$route.query.user_id",this.$route.query.key)
    // this.queryParam.salesman = this.salesmanList[this.$route.query.key-1]
    this.$forceUpdate()
    // console.log('this.queryParam.salesman',this.queryParam.salesman)
  },
  methods: {
    moment,
    getRoleList() {
      getRoLeList().then(res => {
        const list = res.data.data
        list.forEach(item => {
          if (item.name == '业务员') {
            this.getUserListByRoleId(item.id)
          }
        })
      })
    },
    getUserListByRoleId(role_id) {
      const params = {
        role_id
      }
      getUserList(params).then(res => {
        this.userList = res.data.data
        console.log('getuserlistbyroleid',this.userList)
      })
    },
    showYWYList(record) {
      //alert('待开发')
      this.$router.push({
        path:`/yzumerchant/merchant/salesmaninfo`,
        query:{
          key:record.user_id,
          name:record.salesman
        }
      })
    },
    handleChange3Salesman(val) {
      console.log("val",val)
      console.log("this.queryParam.salesman",this.queryParam.salesman)
      // this.queryParam.salesman = this.salesmanList[this.$route.query.user_id-1].label
    },
    // 查看详情
    open(e) {
      this.item = e
      console.log('------------------', e)
      this.visibles = true
    },
      // 搜素模糊查询
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      this.visible = true
      this.mdl = { ...record }
      console.log('this.mdl',this.mdl)
    },
     // 删除
    confirm(e) {
      // const form = this.$refs.createModal.form
      console.log(e);
      merchantApi.MerchantDel({id: e.id}).then(res => {
        if(res.ret == 200) {
          // 刷新表格
          this.$refs.table.refresh()
          this.$message.success('删除成功');
        }
      }).catch(error => {
        console.log('-------------error------------', error)
      })
    },
    cancel(e) {
      console.log(e);
      this.$message.error('已取消');
    },
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    // 创建
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('+++values+++', values)
          new Promise((resolve, reject) => {
            merchantApi.MerchantSave(values).then(value => {
              if (value) {
                resolve()
              } else {
                this.confirmLoading = false
              }
            })
          }).then(res => {
            this.visible = false
            this.confirmLoading = false
            // 重置表单数据
            form.resetFields()
            // 刷新表格
            this.$refs.table.refresh()
    
            this.$message.success(values.id > 0 ? '修改成功' : '新增成功')
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    // 重置
    reset () {
      const form = this.$refs.createModal.form
      this.queryParam = {}
        // 重置表单数据
      form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
  },
}
</script>
<style scoped>
/* 文字溢出隐藏并显示省略号 */
.textfont{
  width: 200px;
  height: 40px;
  /* height: 100%; */
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp:2; /* 设置行数 */
	-webkit-box-orient:vertical;
}
</style>
